﻿using CKS.Core.Framework;
using CKS.PLC.Action.Subscription.OP080;
using FreeSql;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ZR.Model.Models.ProductionControl;

namespace CKS.PLC.Action.Subscription.OP80
{
    /// <summary>
    /// 动作编号1
    /// 码垛机料架数据
    /// </summary>
    public class DB3041_Work01Action : OP80ActionBase
    {
        public DB3041_Work01Action(DecodeValue _value) : base(_value)
        {
        }
        public override void Execute()
        {
            var replayDB = 3040;
            var replayAction = 10;

            var operDB = 3041;
            var operAction = 1;

            var result = Value.Value.ToInt();
            
            var replayPos = Value.GetPosition(replayDB, replayAction, 0);
            
            var shelfCodePos1 = Value.GetPosition(operDB, operAction, 1);
           
            var shelfCodePos2 = Value.GetPosition(operDB, operAction, 3);
            

            if (result == 1)
            {
                int shelfCode1 = Value.GetLinkData(1).ToInt();
                int shelfCode2 = Value.GetLinkData(3).ToInt();

                var arr1 = Value.GetLinkData(2).Adapt<List<string>>();//码垛机1号料架盖板码
                var arr2 = Value.GetLinkData(4).Adapt<List<string>>();//码垛机2号料架盖板码

                //查询 码垛机料架明细 
               var shelf1 = BuildShelfPalletizer(shelfCode1);
               var shelf2 = BuildShelfPalletizer(shelfCode2);

                for (int i = 0; i < PalletizerCellCount; i++)
                {
                    var cellofShelf1 = shelf1[i];
                    var code1 = arr1[i];
                    var cellofShelf2 = shelf2[i];
                    var code2 = arr2[i];
                    cellofShelf1.CoverCode = code1;
                    cellofShelf2.CoverCode = code2;
                }
                conn.Update<CksShelfPalletizer>().SetSource(shelf1).UpdateColumns(a=>a.CoverCode).ExecuteAffrows();
                conn.Update<CksShelfPalletizer>().SetSource(shelf2).UpdateColumns(a => a.CoverCode).ExecuteAffrows();
             

                EventBus.AddLog("OP80请求保存-码垛机料架");
                AckWriteInt16(replayPos, 1);
            }
            else
            {
              
                AckWriteInt16(replayPos, 0);
                logger.LogInformation($"OP80请求保存-码垛机料架-信号重置");
            }
        }
    }
}
